package com.test.latitudex.utilities;

import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;

public class LocationBroadcastReceiver extends BroadcastReceiver {

	private static final String TAG = "LocationBroadcastReceiver";
	private static final String PREFS_NAME = "MyPrefs";
	private static int pollingInterval = 600 * 1000;
	private static int pollingDuration = 45 * 1000;
	final public static String ONE_TIME = "onetime";
	static String GPSLocationProvider = LocationManager.GPS_PROVIDER;
	static String networkLocationProvider = LocationManager.NETWORK_PROVIDER;
	static String userId;
	static LocationManager locationManager;
	static LocationListener locationListener;
	static Context ctx;
	static String serverPath = "http://awseb-e-q-awsebloa-czyxqbdjmzxo-1771358255.us-west-2.elb.amazonaws.com/webresources/location";
	static double minTime, minDist;
	static PowerManager.WakeLock wl;
	static PowerManager pm;
	static ArrayList<Location> locations = new ArrayList<Location>();
	Handler myHandler = new Handler();
	Runnable myRunnable = new Runnable() {
		public void run() {
			try {
				Location retVal = null;
				float acc = Float.MAX_VALUE;
				locationManager = (LocationManager) ctx
						.getSystemService(Context.LOCATION_SERVICE);
				locationManager.removeUpdates(locationListener);
				for (Location l : locations) {
					if (l.getAccuracy() < acc) {
						retVal = l;
					}
				}
				sendRequest(retVal.getLatitude(), retVal.getLongitude(),
						retVal.getAltitude(), retVal.getAccuracy(), ctx);
			} catch (Exception e) {
				e.printStackTrace();
				Log.e(TAG, "Run failed");
			}
		}
	};

	public LocationBroadcastReceiver() {
	}

	public LocationBroadcastReceiver(Context context) {
		ctx = context;
	}

	public LocationBroadcastReceiver(Context context, int mt, int md, String uId) {
		ctx = context;
		userId = uId;
	}

	private void sendRequest(final double lat, final double lot,
			final double alt, final double acc, final Context ctx) {
		try {
			new Thread(new Runnable() {
				public void run() {

					Log.i(TAG,
							"Sending request to server"
									+ " at "
									+ new Date(System.currentTimeMillis())
											.toString()
									+ " "
									+ new Time(System.currentTimeMillis())
											.toString());
					try {

					} catch (Exception e) {
						Log.e(TAG, e.getMessage());
					}
					try {
						RegistrationManager.getEntity().putData(lat, lot, alt,
								acc, ctx);
					} catch (Exception e) {
						Log.e(TAG, e.getMessage());
					}
					synchronized (wl) {
						if (wl != null) {
							Log.v(TAG, "Releasing wakelock");
							try {
								if (wl.isHeld()) {
									wl.release();
								}

							} catch (Throwable th) {
							}
						} else {
							Log.e(TAG, "Wakelock reference is null");
						}
					}
				}
			}).start();
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		try {
			Log.i(TAG,
					"Service awake" + " at "
							+ new Date(System.currentTimeMillis()).toString()
							+ " "
							+ new Time(System.currentTimeMillis()).toString());
			pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
			wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
			// Acquire the lock
			wl.acquire();
			ctx = context;
			locationManager = (LocationManager) context
					.getSystemService(Context.LOCATION_SERVICE);
			locationListener = new LocationListener() {
				public void onLocationChanged(Location location) {
					locations.add(location);
					Log.i(TAG,
							"Location data received from:"
									+ location.getProvider() + " at "
									+ new Date(location.getTime()).toString()
									+ " "
									+ new Time(location.getTime()).toString());
				}

				public void onStatusChanged(String provider, int status,
						Bundle extras) {
				}

				public void onProviderEnabled(String provider) {
				}

				public void onProviderDisabled(String provider) {
				}
			};

			SharedPreferences settings = context.getSharedPreferences(
					PREFS_NAME, 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.putString("LastUpdate",
					new Date(System.currentTimeMillis()).toString() + " "
							+ new Time(System.currentTimeMillis()).toString());
			editor.commit();

			// You can do the processing here.
			final Timer myTimer = new Timer();
			myTimer.schedule(new TimerTask() {
				@Override
				public void run() {
					myHandler.post(myRunnable);
					myTimer.cancel();
					myTimer.purge();
				}
			}, pollingDuration, Integer.MAX_VALUE);
			locationManager.removeUpdates(locationListener);
			locations.clear();
			locationManager.requestLocationUpdates(networkLocationProvider, 0,
					0, locationListener);
			locationManager.requestLocationUpdates(GPSLocationProvider, 0, 0,
					locationListener);
		} catch (Exception e) {
			Log.e(TAG, "Reinit");

		}

	}

	public static void SetAlarm(Context context) {
		Log.i(TAG,
				"Service started" + " at "
						+ new Date(System.currentTimeMillis()).toString() + " "
						+ new Time(System.currentTimeMillis()).toString());
		AlarmManager am = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, LocationBroadcastReceiver.class);
		PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
		am.setRepeating(AlarmManager.RTC_WAKEUP,
				System.currentTimeMillis() + 10000, pollingInterval, pi);
	}

	public static void CancelAlarm(Context context) {
		Log.i(TAG,
				"Service stopped" + " at "
						+ new Date(System.currentTimeMillis()).toString() + " "
						+ new Time(System.currentTimeMillis()).toString());
		Intent intent = new Intent(context, LocationBroadcastReceiver.class);
		PendingIntent sender = PendingIntent
				.getBroadcast(context, 0, intent, 0);
		AlarmManager alarmManager = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		alarmManager.cancel(sender);
	}

}
